ROLE_NONE = 0
ROLE_USER = 100
ROLE_STAFF = 200

Router = require('koa-router')
router = new Router()

log = require('./log')
permissions = require('./permissions').permissions
errors = require('./errors')

UserService = require('./service/UserService')
UserHandler = require('./http/UserHandler')
PageHandle = require('./http/PageHandle')
TopicHandle = require('./http/TopicHandle')

auth = (authRequired, permission, isPage) ->
    return (next)->
        try
            unless authRequired
                yield next
            else
                if this.state.userId
                    if permission and not (this.state.userPermissions and permission.id in this.state.userPermissions)
                        log.user.debug 'expect permission', permission.id
                        return this.status = 403
                    else
                        yield next
                else
                    if isPage
                        this.redirect('/sign-in?src=' + this.url)
                    else
                        this.status = 401
        catch e
            if e instanceof errors.UserError
                this.status = 400
                if isPage
                    this.render('400', {message: e.message})
                else
                    this.body = e.describe()
            else
                log.system.error e
                if isPage
                    this.render('500', {message: e.message})
                else
                    this.status = 500


router.get '/', auth(false), PageHandle.toIndex

# =========================================
# 帖子
# =========================================

router.get '/topic/new', auth(true, null, true), TopicHandle.toCreateTopic
router.post '/topic/new', auth(true), TopicHandle.gCreateTopic
router.get '/topic/:id', auth(true, null, true), TopicHandle.toTopicDetail
router.get '/topic/:id/edit', auth(true, null, true), TopicHandle.toEditTopic
router.put '/topic/:id/edit', auth(true), TopicHandle.gEditTopic
router.delete '/topic/:id', auth(true), TopicHandle.gDeleteTopic


# =========================================
# 账户
# =========================================

# 顾客登录页面
router.get '/sign-in', auth(false), UserHandler.toSignIn
router.post '/sign-in', auth(false), UserHandler.gSignIn

router.get '/sign-up', auth(false), UserHandler.toSignUp
router.post '/sign-up', auth(false), UserHandler.gSignUp
#router.post '/sign-out', auth(true), UserHandler.gSignOut
router.get '/sign-out', auth(true, null, true), UserHandler.gSignOut
#router.get '/ping', auth(true), UserHandler.gPing
#router.post '/account-changed', UserHandler.pAccountChanged


exports.getRouter = -> router